import axios from 'axios';
import { message } from 'antd';
import useAuthStore from '../stores/authStore';

// 创建 axios 实例
const request = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 10000, // 请求超时时间
  withCredentials: true,  // 必须设置为 true
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response?.status === 401) {
      const currentPath = window.location.pathname;
      const store = useAuthStore.getState();
      
      if (currentPath !== '/login' && 
          store.isAuthenticated && 
          !error.config.url.includes('/api/teacher/login') &&
          !error.config.url.includes('/api/teacher/logout')) {
        
        const isLoggingOut = localStorage.getItem('isLoggingOut');
        if (!isLoggingOut) {
          localStorage.setItem('isLoggingOut', 'true');
          store.logout().finally(() => {
            localStorage.removeItem('isLoggingOut');
            window.location.href = `/login?callback=${encodeURIComponent(currentPath)}`;
            message.error('登录已过期，请重新登录');
          });
        }
      }
    }
    return Promise.reject(error);
  }
);

// 封装通用请求方法
const http = {
  get: (url, config) => request.get(url, config),
  post: (url, data, config) => request.post(url, data, config),
  put: (url, data, config) => request.put(url, data, config),
  delete: (url, config) => request.delete(url, config),
};

export const BASE_URL = '/';  // 这个用于静态资源

export default http; 